/**
 * @description 请求配置
 * @author WangLongFei/Alisdon <920124512@qq.com>
 */
import axios from 'axios';
import message from './message.js';
import { removeToken } from './auth.js';
import JSONBig from 'json-bigint';
import router from '@/router/index'
import Cookies from 'js-cookie';
class REQUEST {
  static request(type, url, data = {}, config = {}) {
    _requestAxios(type, { url, config, data });
  }
  static get(url, data, config = {}) {
    // console.log(config)
    // console.log(data)
    config.params = data;
    return _requestAxios('get', { url:url, data:data, config:config });
  }
  static post(url, data, config = {}) {
    return _requestAxios('post', { url:url, data:data, config:config });
  }
  static put(url, data, config = {}) {
    return _requestAxios('put', { url:url, data:data, config:config });
  }
  static delete(url, data, config = {}) {
    return _requestAxios('delete', { url:url, data:data, config:config });
  }
  static upload(url,file, config = {}) {
    Object.assign(config,{
      headers:{'Content-Type':'multipart/form-data',path:this.uppath}
    });
    let forms = new FormData()
    forms.append('fileName',file);
    return _requestAxios('post', { url:url, data:forms, config:config });
  }
  static download(url, data, fileName, cb) {
    const config = {
        responseType: 'blob',
    };
    _requestAxios('get', { url, data, config }).then((res) => {
        if (cb) {
            cb();
        }
        console.log(res)
        const blob = new Blob([res.data]);
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = fileName || _getFileName(res);
        link.style.display = 'none';
        document.body.appendChild(link);
        link.click();
        window.URL.revokeObjectURL(link.href);
        document.body.removeChild(link);

        function _getFileName(res) {
            const { headers } = res;
            const contentDisposition = headers['content-disposition'];
            const reg = /(filename=)(\S)*(;)?/g;
            const fileNameArr = contentDisposition.match(reg);
            console.log(fileNameArr)
            if (fileNameArr.length < 1) {
                return 'template.txt';
            }
            const fileNameStr = fileNameArr[0].replace(';', '');
            const fileName = fileNameStr.replace('filename=', '');
            return decodeURI(fileName);
        }
    });
    return false;
}
}

function _regurl(url) {
  return url.match(/([^/]+)\/(v\d)(\/\S+)/)
}

function _requestAxios(type, { url, config = {}, data = {} }) {
  config.headers = Object.assign(
    {
      'Content-Type': 'application/json'
    },
    config.headers
  );
  // console.log(console.log(config))

  _formatRequestData (type,config,data);
  let requestConfig = Object.assign(config,{method:type.toLowerCase(),url})
  return axios(requestConfig).then(res=>_requestThen(config, res)).catch(error=>_requestCatch(config, error))

  function _requestThen(config, res) {
    return new Promise((resolve, reject) => {

      if (!config.responseType || config.responseType === 'json') {
        if (res.data.code === 0 && res.data.subCode === 0) {
          resolve(res.data);
        } else {
          const vegaErrorCode = [
            '330000011',
            '330000012',
            '330000013',
            '330000014',
            '330000015',
            '330000016',
            '330000017',
            '330000018',
            '330000019',
            '331040003', // gtoken not allow empty
            '331040007' // gtoken not existed
          ];
          if (vegaErrorCode.includes('' + res.data.subCode) || vegaErrorCode.includes('' + res.data.code)) {
            removeToken();
            // return (location.href = '/');
          }
          resolve(res);
        }
      } else {
        if (res && res.data) {
          resolve(res);
        }
      }
    });
  }

  function _formatRequestData(type, config, data) {
    const isBody = ['PUT', 'put', 'POST', 'post', 'PATCH', 'patch'];
    let resultData = {};

    if (isBody.includes(type)) {
      resultData = _trimParams(data) || {};

      if (config.headers && config.headers['Content-Type']
        &&config.headers['Content-Type'].indexOf('application/x-www-form-urlencoded') > -1) {
        resultData = _formatParams(data);
      }
      config.data = resultData;
    } else {
      data = config.params || data;
      config.params = _trimParams(data) || {};
      resultData = config;
    }
    return resultData;
  }

  function _trimParams(data) {
    if (data.constructor === Object) {
      for (let i in data) {
        if (typeof data[i] === 'string') {
          data[i] = data[i].trim();
        }
      }
    }

    return data;
  }

  function _formatParams(data) {
    if (data.constructor === Object) {
      const arr = [];

      for (const i in data) {
        arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(data[i]));
      }

      data = arr.join('&');
    }

    return data;
  }

  function _requestCatch(config, error = {}) {
    return new Promise((resolve, reject) => {
      // console.log(error)
      if (!error.isCancel) {
        if (config.needReject) {
          reject(error);
        } else {
          const messageText = ((error.response || {}).data || {}).message;
          message.error(messageText || '请求失败');
        }
      }
    });
  }
}

axios.defaults.withCredentials = true;
axios.interceptors.request.use(config => {
  config.transformResponse = [
    function(data){
      if (config.responseType == 'blob') {
        return data;
      }
      return JSONBig.parse(data);
    }
  ];
  return config;
}, error => {
  return Promise.reject(error);
});

axios.interceptors.response.use(response => {
  !response.config.removeToken;
   if(response.data.code === 102) {
    Cookies.remove('id')
    removeToken()
    router.push('/login')
  }
  return response;
}, error => {
  if (axios.isCancel(error)) {
    return Promise.reject({ isCancel: true });
  } else {
    return Promise.reject(error);
  }
});

export default REQUEST;
